import 'dart:convert';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:dio_log/interceptor/dio_log_interceptor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_li_ke_jie/entity/base_response.dart';
import 'package:flutter_li_ke_jie/router/router.dart';
import 'package:flutter_li_ke_jie/utils/navigator_util.dart';
import 'package:flutter_li_ke_jie/utils/sputil.dart';

import '../../utils/loading_utils.dart';
import '../../utils/nav_key.dart';
import '../../utils/path_util.dart';
import '../utils/toast.dart';

class XHttp {
  XHttp._internal();

  ///网络请求配置
  static final Dio dio = Dio(BaseOptions(
    baseUrl: "http://192.168.9.97:8080/",
    // baseUrl: "http://192.168.0.107:8080/",
    connectTimeout: 60000,
    receiveTimeout: 60000,
  ));

  ///初始化dio
  static void init() {
    ///初始化cookie
    PathUtil.getDocumentsDirPath().then((value) {
      var cookieJar =
          PersistCookieJar(storage: FileStorage(value + "/.cookies/"));
      dio.interceptors.add(CookieManager(cookieJar));
    });

    dio.interceptors.add(DioLogInterceptor());
    //添加拦截器
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options, handler) {
      // print("请求之前");
      //添加请求头
      options.headers["device"] = SPUtil.getDevice();
      options.headers["deviceId"] = SPUtil.getDeviceId();
      options.headers["Authorization"] = SPUtil.getToken();
      return handler.next(options);
    }, onResponse: (Response response, handler) {
      // print("响应之前");
      Map<String,dynamic> data = response.data;
      if(data.isNotEmpty){
        BaseResponse<dynamic> baseResponse = BaseResponse.fromJson(data);
        if(baseResponse.code==401){
          //返回到登录页
          Future.delayed(Duration(seconds:0)).then((onValue)  {
            BuildContext? context = NavKey.navKey.currentState?.overlay?.context;
            if(context!=null){
              NavigatorUtil.goAndFinishAll(context, LOGIN_PAGE);
            }
          });

        }
      }
      return handler.next(response);
    }, onError: (DioError e, handler) {
      // print("错误之前");
      //关闭
      LoadingUtils.dismiss();
      handleError(e);
      return handler.next(e);
    }));
  }

  ///error统一处理
  static void handleError(DioError e) {
    switch (e.type) {
      case DioErrorType.connectTimeout:
        print("连接超时");
        break;
      case DioErrorType.sendTimeout:
        print("请求超时");
        break;
      case DioErrorType.receiveTimeout:
        print("响应超时");
        break;
      case DioErrorType.response:
        print("出现异常");
        break;
      case DioErrorType.cancel:
        print("请求取消");
        break;
      default:
        print("未知错误");
        break;
    }
    ToastUtils.error("$e");
  }

  ///get请求
  static Future get(String url, [Map<String, dynamic> params = const {},bool showLoading=true]) async {
    Response response;
    if(showLoading){
      //请求框
      LoadingUtils.show();
    }
    if (params != null) {
      response = await dio.get(url, queryParameters: params);
    } else {
      response = await dio.get(url);
    }
    if(showLoading){
      //关闭
      LoadingUtils.dismiss();
    }
    return response.data;
  }

  ///post 表单请求
  static Future post(String url, [Map<String, dynamic> params = const {},bool showLoading=true]) async {
    if(showLoading){
      //请求框
      LoadingUtils.show();
    }
    Response response = await dio.post(url, queryParameters: params);
    if(showLoading){
      //关闭
      LoadingUtils.dismiss();
    }
    return response.data;
  }

  ///post body请求
  static Future postJson(String url, [Map<String, dynamic> data=const {},bool showLoading=true]) async {
    if(showLoading){
      //请求框
      LoadingUtils.show();
    }
    Response response = await dio.post(url, data: data);
    if(showLoading){
      //关闭
      LoadingUtils.dismiss();
    }
    return response.data;
  }

  ///下载文件
  static Future downloadFile(urlPath, savePath,{bool showLoading=true}) async {
    Response? response;
    try {
      if(showLoading){
        //请求框
        LoadingUtils.show();
      }
      response = await dio.download(urlPath, savePath,
          onReceiveProgress: (int count, int total) {
        //进度
        print("$count $total");
      });
      if(showLoading){
        //关闭
        LoadingUtils.dismiss();
      }
    } on DioError catch (e) {
      if(showLoading){
        //关闭
        LoadingUtils.dismiss();
      }
      handleError(e);
    }
    return response?.data;
  }
}
